from django.contrib.syndication import feeds
from django.http import HttpResponse, Http404
from django.utils import feedgenerator

from namedquerysets import NamedQuerySet, parse_querystring

def feed(request, url, feed_dict=None):
    if feed_dict is None:
        feed_dict = dict((k,NamedQuerySetFeed) for k
                          in NamedQuerySet.named_querysets.keys())
    if not feed_dict:
        raise Http404, "No feeds are registered."

    try:
        slug, param = url.split('/', 1)
    except ValueError:
        slug, param = url, ''

    try:
        f = feed_dict[slug]
    except KeyError:
        raise Http404, "Slug %r isn't registered." % slug

    try:
        feedgen = f(slug, request.path, request.GET.urlencode()).get_feed(param)
    except feeds.FeedDoesNotExist:
        raise Http404, "Invalid feed parameters. Slug %r is valid, but other parameters, or lack thereof, are not." % slug

    response = HttpResponse(mimetype=feedgen.mime_type)
    feedgen.write(response, 'utf-8')
    return response

def rss(request, url):
    return feed(request, url)

def atom(request, url):
    feed_dict = dict((k,NamedQuerySetAtomFeed) for k
                      in NamedQuerySet.named_querysets.keys())
    return feed(request,url,feed_dict)

class NamedQuerySetFeed(feeds.Feed):
    
    feed_type = feedgenerator.DefaultFeed

    def __init__(self, slug, feed_url, querystring):
        self.slug = slug
        self.feed_url = "%s?%s" % (feed_url, querystring)
        self.querystring = querystring
        self.title_template_name = self.title_template or ('feeds/%s_title.html' % slug)
        self.description_template_name = self.description_template or ('feeds/%s_description.html' % slug)
        self.context = NamedQuerySet.get_context(slug, parse_querystring(querystring))
    
    def title(self):
        return self.context['namedqueryset']['filtered']['title']
    
    def link(self):
        return self.feed_url
    
    def description(self):
        return self.context['namedqueryset']['filtered']['title']
    
    def items(self):
        return self.context['namedqueryset']['filtered']['queryset']
    
    def item_pubdate(self, item):
        try:
            return item.get_pubdate()
        except AttributeError:
            return None
    
    def item_author_link(self, item):
        try:
            return feeds.add_domain(item.get_author_link())
        except AttributeError:
            return None
    
    def item_author_name(self, item):
        try:
            return item.get_author_name()
        except AttributeError:
            return None
    
    def item_enclosure_url(self, item):
        try:
            return feeds.add_domain(item.get_enclosure_url())
        except AttributeError:
            return None
        
    def item_enclosure_length(self, item):
        try:
            return item.get_enclosure_length()
        except AttributeError:
            return None
    
    def item_enclosure_mime_type(self, item):
        try:
            return item.get_enclosure_mime_type()
        except AttributeError:
            return None
        
    def item_categories(self, item):
        try:
            return item.get_categories()
        except AttributeError:
            return None
    
    def item_copyright(self, item):
        try:
            return item.get_copyright()
        except AttributeError:
            return None

class NamedQuerySetAtomFeed(NamedQuerySetFeed):
    feed_type = feedgenerator.Atom1Feed
